<template>
  <div id="main" >
    <van-sticky>
      <div class="nav">
        <img :src="back" alt="" @click="handleBack" class="back" />
        <van-search
          style="height: 40px"
          v-model="searchValue"
          shape="round"
          background="#f29600"
          @clear="handleClear"
          placeholder="搜索你感兴趣的话题或爱好"
        >
        </van-search>
        <div class="nav-btn">
          <span @click.prevent="handleSearch">搜索</span>
        </div>
      </div>
    </van-sticky>
    <div  v-loading="reLoading">
      <!-- 处理数据开始 -->
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh" >
          <van-list
          
          class="list-item"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad">
          <div
            class="two-part-main"
            v-for="(item,index) in dynamicList"
            :key="index">
          <div class="two-part-title" @click="gotoPersonal(item)">
            <div class="avatar" :style="{backgroundImage: `url(${item.avatar ? store.state.imgUrl + item.avatar : logo})`}"></div>
            <!-- <van-image :src="item.avatar ? store.state.imgUrl + item.avatar : logo" round width="38" height="38" style="margin-right:5px"  /> -->
            <div>
              <div>{{ item.name }}<span class="me" v-if="item.isOwn == 0">我</span></div>
              <div v-if="!item.isOwn == 0">
                <span>{{ item.createTime }}</span>
                <span v-if="item.isAttention === 1 " style="padding-left:2px">已关注</span>
                <span v-if="item.isAttention === 0 " style="padding-left:2px">未关注</span>
              </div>
            </div>
          </div>
          <!-- <div class="desc" @click="handleDetail(item.id)">{{ item.title }}</div> -->
          <div class="desc" v-if="item.title"  @click="handleDetail(item.id)">{{ item.title }}</div>
          <div class="descDetail" style="font-size:14px;color:#a6a6a6;padding-top:5px"  @click="handleDetail(item.id)">{{ item.description }}</div>
          <div class="image-list">
            <div
              class="item-list-item"
              v-for="(dynamicItem, index) in item.children ? item.children.slice(0,3) : []"
              :key="index"
              @click="handleImageClick(item.children, index)"
              :style="{backgroundImage: `url(${dynamicItem})`}"
            >
            <!-- <img
                :src="dynamicItem"
                alt=""
                width="100%"
                height="100%"
              /> -->
              <div class="more" v-if="item.children.length > 2 && index === 2">
                <span>+{{ item.children.length - 3 }}</span>
              </div>
            </div>
          </div>
          <div class="remark">
            <div @click="gotodz(item,index)">
              <img :src="remarkList.urldz" width="15" v-if="!item.isLike"/>
              <img :src="remarkList.urldzlove" v-if="item.isLike" width="15"/>
              <div>{{ item.likeNum }}</div>
            </div>
            <div @click="handleDetail(item.id)">
              <img :src="remarkList.urlpl" width="15"/>
              <div>{{ item.commentNum }}</div>
            </div>
            <div @click="addCollect(item,index)">
              <img :src="remarkList.urlsc" width="16" v-if="!item.isCollect"/>
              <img :src="remarkList.urlsclove" width="16" v-if="item.isCollect"/>
              <div>{{ item.collectNum }}</div>
            </div>
            <div @click="gotozf(item)">
              <img :src="remarkList.urlzf" width="15"/>
              <div>分享</div>
            </div>
            <img src="@/assets/remark/jb.png" @click="gotojb(item)" v-if="!item.isOwn == 0">
          </div>
          <Report ref="report" v-if="jbvisible && item.id === clickId"  :type="type" @close="close" :token="token"></Report>
          </div>
          </van-list>
      </van-pull-refresh>
      
      <!-- 处理数据结束 -->
    </div>
    <div class="publish" @click="handlePublish">
      <img src="@/assets/publish.png" />
    </div>
    <van-share-sheet
           v-model="showShare"
           title="立即分享给好友"
           :options="options"
           @select="onSelect"
       />
  </div>
</template>

<script>
import { ImagePreview } from "vant";
import { warningJBArr } from "@/const/index";
import {queryDynamicListApi,updateLikes,addCollect} from '@/api/share'
import Report from "./report.vue";
import {Toast} from "vant";
import store from '@/store'

import {antiShake} from '@/utils/antie.js'//防抖函数

// import { nextTick } from 'vue';
export default {
  components:{Report},
  data() {
    return {
      dynamicList: [],
      basicImgUrl: "https://debug.yasee.com.cn",
      searchValue: "",
      back: require("@/assets/search/back.png"),
      remarkList: {
        urlsclove: require('@/assets/remark/sc_love.png'),
        urldzlove: require('@/assets/remark/dz_love.png'),
        urldz: require('@/assets/remark/dz.png'),
        urlpl: require('@/assets/remark/pl.png'),
        urlsc: require('@/assets/remark/sc.png'),
        urlzf: require('@/assets/remark/zf.png'),
      },
      collect: false,
      Like: false,
      jbvisible: false,
      jbList: warningJBArr,
      id:'',
      finished:false,
      loading:false,
      current: 1, // 获取下一页数据current
      size: 10,
      clickId:'',
      type:'',
      token:'',
       options: [
        {name: '微信', icon: 'wechat', openType: 'share'},
        {name: 'QQ', icon: 'qq', openType: 'share'},
        {name: '微博', icon: 'weibo'},
        {name: '复制链接', icon: 'link'},
      ],
      showShare:false,
      store:store,
      logo: require("@/assets/tx.png"),
      isLoading:false,
      reLoading:false
    };
  },
  mounted() {
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === 'share') {
        this.getInfoFromFlutter(info);
        
      }
    };
     this.id = !this.getParam("id") ? "" : this.getParam("id")
     this.token = !this.getParam("token") ? "" : decodeURI(this.getParam("token"))
    // this.getDataList()
  },
  created() {},
  methods: {
    getParam(name) {
          if (window.location.hash.indexOf("?") != -1) {
            const query = window.location.hash.split("?")[1];
            const vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                    if (pair[0] == name) {
                        return pair[1];
                    }
                }
        } else {
            return "";
        }
    },
     getInfoFromFlutter(info) {
        let data = JSON.parse(info)
        if (data.param.succeed == 1) {
          this.$toast.success('分享成功')
        } else {
          this.$toast.fail('已取消分享')
        }
      },
    handleClear() {
      this.handleSearch()
    },
    handleSearch: antiShake( function (){
      this.dynamicList = []
      this.current = 1
      this.loading = false
      this.finished = false
      this.onLoad()
    }),
    handleBack() {
      this.$router.go(-1);
      let message = {
        action: 'showBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    gotojb(item) {
      this.jbvisible = true
      this.clickId = item.id
      this.type = 'content'
      this.$nextTick(()=>{
        // console.log(this.$refs)
        this.$refs.report[0].init(item)
      })
      
    },
    close() {
      this.jbvisible = false
    },
    handleDetail(id) {
      //动态详情
      this.$router.push({ path: "/trendsDetail", query:{
            id:id
           
      } });
      //  let data = {
      //   action: 'pushPage',
      //   param: {
      //     type: 'web',
      //     name:'/home/share/trendsDetail',
      //     url: `${this.$store.state.linkUrl}/trendsDetail?id=${id}&token=${this.token}`
      //   }
      // }
      // getInfoFromVue.postMessage(JSON.stringify(data))
    },
    handleImageClick(item, index) {
      const imageUrls = item.map((image) => image);
      ImagePreview({
        images: imageUrls,
        startPosition: index,
        showIndicators:true,
        closeable:true
      });
    },
   async onLoad(){
      const param = { 
        id: this.id ,
        size: this.size,
        current: this.current,
        search: this.searchValue,
        token:this.token
        // routerld:-3,
        // commentType:1
      }
      this.loading = true
      const {data} = await queryDynamicListApi(param)
        if (data !== null) {
          
        const {records} = data
        this.dynamicList.push(...records)
        
        this.loading = false
        this.isLoading = false
          if (this.reLoading) {
          this.$toast('刷新成功')
          this.reLoading = false
         }
        if (records.length > 0) {
          this.current += 1
        } else {
          this.finished = true
        }
      } else {
        this.finished = true
      }
     
    },
    //点赞
    gotodz: antiShake( function (item,index)  {
      let data = {
        id: item.id,
        type: 0 ,//文章，动态，视频是0 评论是1,
        token:this.token
      }
      updateLikes(data).then((res) => {
        if (res.code == 0) {
          if (item.isLike) {
           this.$toast.fail('已取消点赞')
          }else{
           this.$toast.success('点赞成功')
          }
          item.likeNum += !item.isLike ? 1 : -1;
          this.dynamicList[index].isLike = !this.dynamicList[index].isLike
        }
      }).catch((err) => {
        this.$toast.fail('点赞失败')
      })
    }),
    // 收藏
    addCollect: antiShake(  function (item,index)  {
        let data = {
          id: item.id,
          type: 0 ,//文章，动态，视频是0 评论是1
          token:this.token
      }
      addCollect(data).then((res) => {
        if (res.code == 0) {
            if (item.isCollect) {
              this.$toast.fail('取消收藏！')
            }else{
            this.$toast.success('收藏成功')
            }
          item.collectNum += !item.isCollect ? 1 : -1;
          this.dynamicList[index].isCollect = !this.dynamicList[index].isCollect

        }
      }).catch((err) => {
        this.$toast.fail('收藏失败')
      })
    }),
     handlePublish() {
      this.$router.push({path: "/publish", query: {commentType: 1}});
      //  let commentType = 1
      //  let data = {
      //   action: 'pushPage',
      //   param: {
      //     type: 'web',
      //     name:'/home/share/trends/publish',
      //     url: `${this.$store.state.linkUrl}/publish?commentType=${commentType}&token=${this.token}`
      //   }
      // }
      // getInfoFromVue.postMessage(JSON.stringify(data))
    },
     gotozf(item){
      //  this.showShare = true
       let message = {
        action: 'share',
        param: {
          type: "link",            //必填
          title: item.title,          //必填
          name: '/home/share/index',
          subtitle: item.description,
          link: "http://192.168.110.105:9033/#/trendsDetail?"+item.id,//动态列表的详情?id:''
          callback: 1
        }
      }
      // console.log(message)
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
     onSelect(option) {
      Toast(option.name);
      if (option.name === '微信') {
        window.location.href = 'weixin://';
      } else if (option.name === 'qq') {
        //跳转qq链接
      } else if (option.name === '微博') {
        //跳转微博的链接
      } else if (option.name === '复制链接') {
        //复制链接
        this.copyLink()
      }
      this.showShare = false;
    },
     copyLink() {
      const link = window.location.href; // 要复制的链接
      // console.log(link)
      // 使用Vant的Clipboard组件的copy方法复制链接
      // this.$vant.Clipboard.copy(link)
      //   .then(() => {
      //     this.$toast('链接已复制'); // 复制成功提示
      //   })
      //   .catch(() => {
      //     this.$toast('复制失败'); // 复制失败提示
      //   });
      let inputNode = document.createElement('input')  // 创建input
      inputNode.value = link // 赋值给 input 值
      document.body.appendChild(inputNode) // 插入进去
      inputNode.select() // 选择对象
      document.execCommand('Copy') // 原生调用执行浏览器复制命令
      inputNode.className = 'oInput'
      inputNode.style.display = 'none' // 隐藏
      this.$toast.success('复制成功')
    },
     onRefresh(){
      this.current = 1
      this.reLoading = true
      this.dynamicList = []
      
      this.onLoad()
      
     
      
    },
    gotoPersonal(item) {
      if (item.isOwn == 0) {//跳转到自己的个人主页
        this.$router.push({path: '/personalPage',query:{}})
      }else{//跳转到别人主页的个人主页
        this.$router.push({path: '/visitPersonal',query:{obj:JSON.stringify(item)}})
      }
      
      // let message = {
      //   action: 'hiddenBottom',
      //   param: {}
      // }
      // getInfoFromVue.postMessage(JSON.stringify(message))
    },
  },
};
</script>

<style lang="less" scoped>
#main {
  // padding: 0 10px;
  height: 100vh;
  width: 100%;
  .nav {
    display: flex;
    // height: 40px;
    background: #f29600;
    justify-content: space-around;
    align-items: center;
    flex-direction: row;
    padding: 4px 16px 7px 16px;
    .back {
      cursor: pointer;
    }
    .van-search {
      padding: 0;
      background-color: #fff;
      width: 283px;
      height: 33px;
      margin: 0 6px 0 15px;
    }
    @media screen and (max-width: 389px) {
      .van-search {
        padding: 0;
        background-color: #fff;
        width: 260px;
        height: 33px;
        margin: 0 5px 0 15px;
      }
    }
    @media screen and (max-width: 374px) {
      .van-search {
        padding: 0;
        background-color: #fff;
        width: 220px;
        height: 33px;
        margin: 0 3px 0 10px;
      }
    }

    .nav-btn {
      height: 22px;
      font-size: 15px;
      padding: 3px 7px;
      border-radius: 3px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #fff;
      cursor: pointer;
    }
  }

  .two-part-main {
    padding: 10px 10px 0 10px;
    position: relative;

    // .jb-dialog {
    //   z-index: 999;
    //   position: absolute;
    //   bottom: 35px;
    //   right: 5px;
    //   width: 268px;
    //   height: 177.05px;
    //   border-radius: 17px;
    //   //background: linear-gradient(180deg, rgba(255, 255, 255, 1) 0%, rgba(255, 184, 112, 0.19) 0%, rgba(255, 141, 26, 0) 100%);
    //   background: #f0f0f0;
    //   .title {
    //     font-size: 20px;
    //     font-weight: 500;
    //     letter-spacing: 0px;
    //     line-height: 28.96px;
    //     color: rgba(0, 0, 0, 1);
    //     text-align: center;
    //     margin: 10px;
    //   }
    //   .jb-item-all {
    //     display: flex;
    //     align-items: center;
    //     justify-slclsj: center;
    //     flex-wrap: wrap;
    //     .jb-item {
    //       width: 110.79px;
    //       height: 28px;
    //       margin-right: 20px;
    //       line-height: 28px;
    //       border-radius: 36px;
    //       background: rgba(255, 231, 191, 1);
    //       text-align: center;
    //       margin-bottom: 12px;
    //     }
    //     .jb-item:nth-of-type(2n + 0) {
    //       margin-right: 0;
    //     }
    //   }
    // }

    .two-part-title {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .avatar{
          border: 1px solid #ebeef5;
          background-size: 100%;
          width: 38px;
          height: 38px;
          border-radius: 50%;
          opacity: 1;
          margin-right:5px;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
      }
      .me{
          background: #ccc6;
          padding: 0 3px;
          font-size: 14px;
          border-radius: 5px;
          color: #9b9494;
          margin: 0 5px;
      }

      > img {
        width: 38px;
        height: 38px;
        margin-right: 8px;
      }

      div:nth-child(1) {
        font-size: 16px;
        font-weight: 500;
        letter-spacing: 0px;
        line-height: 23.17px;
        color: rgba(0, 0, 0, 1);
      }

      div:nth-child(2) {
        font-size: 12px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 17.38px;
        color: rgba(153, 153, 153, 1);
        text-align: left;
      }
    }
     .descDetail{
      //  height: 55px;
          display: -webkit-box;
          -webkit-line-clamp: 3; /* 设置最大行数 */
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          word-wrap: break-word; /* 允许换行 */
          line-height: 1.5; /* 行高，可根据需要进行调整 */
    }

    .desc {
      font-size: 17px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 24.62px;
      color: rgba(0, 0, 0, 1);
      text-align: left;
      vertical-align: top;
      padding-top: 10px;
    }

    .image-list {
      padding: 15px 0;
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: flex-start;

      .item-list-item:nth-of-type(3n + 0) {
        margin-right: 0;
      }

      .item-list-item {
        width: calc((100% - 14px) / 3);
        height: 114px;
        border-radius: 5px;
        margin-right: 7px;
        position: relative;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;

        .more {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 36px;
          height: 26px;
          opacity: 1;
          border-radius: 5px 0px 5px 0px;
          background: rgba(0, 0, 0, 0.47);
          font-size: 12px;
          font-weight: 400;
          letter-spacing: 0.5px;
          line-height: 26px;
          color: rgba(255, 255, 255, 1);
          text-align: center;
        }
      }
    }

    .remark {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #f0f0f0;
      padding-bottom: 10px;

      > img {
        width: 11px;
        height: 11px;
        opacity: 1;
      }

      > div {
        display: flex;
        align-items: center;

        img {
          // width: 12.56px;
          // height: 15.28px;
          opacity: 1;
        }

        > div {
          margin-left: 4px;
          font-size: 12px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 17.38px;
          color: rgba(81, 81, 81, 1);
          text-align: left;
        }
      }
    }
  }

  .publish {
    position: fixed;
    bottom: 50px;
    right: 10px;
    width: 55px;
    height: 55px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(242, 150, 0, 1);
    border-radius: 20px;

    img {
      width: 25px;
      height: 25px;
      opacity: 1;
    }
  }
}
</style>
